/********************************************************************************
 *      Copyright:  (C) 2024 linuxer<linuxer@email.com>
 *                  All rights reserved.
 *
 *       Filename:  temperature.c
 *    Description:  This file 
 *
 *        Version:  1.0.0(17/03/24)
 *         Author:  linuxer <linuxer@email.com>
 *      ChangeLog:  1, Release initial version on "17/03/24 16:52:22"
 *                 
 ********************************************************************************/
#include"temperature.h"

int get_info(char* temp)
{
	char			*ptr=NULL;
	char			buf[1024];
	int				fd=-1;
	DIR				*dirp=NULL;
	struct	dirent	*direntp=NULL;
	char			chip_sn[32];
	int				found=0;
	int				rv=0;
	
	if(rv<0)
	{
		log_error("Fail to get time:%s\n",strerror(errno));
		return -2;
	}

	//获取当前温度
	rv=get_temperature(temp);	
	if(rv<0)
	{
		log_error("Fail to get temperature:%s\n",strerror(errno));
		return -3;
	}

	return rv;
}

//获取温度

int get_temperature(char* temp)
{
	int					rv=0;
	int 				fd=-1;
	char				file_name[64];
	char				buf[1024];
	char				*ptr=NULL;
	char				des[16]="28-";
	char				temp_path[64]="/sys/bus/w1/devices/";
	
	rv=find_file(temp_path,des,file_name);
	
	if(rv<0)
	{
		log_error("Find file  failure: %s\n",strerror(errno));
		return -1;
	}

#if 1 
	
	strncat(temp_path,file_name,sizeof(temp_path)-strlen(temp_path));
	strncat(temp_path,"/w1_slave",sizeof(temp_path)-strlen(temp_path));


	if((fd=open(temp_path,O_RDONLY))<0)
	{
		log_error("Open directory: %s failure: %s\n",temp_path,strerror(errno));
		return -2;
	}

	memset(buf,0,sizeof(buf));
	read(fd,buf,sizeof(buf));
	ptr=strstr(buf,"t=");
	if(!ptr)
	{
		log_error("Can not find the temperature\n");
		return -3;
	}
	ptr+=2;
	sprintf(temp,"%08.4f",atof(ptr)/1000);
	close(fd);	
#endif 
	return rv;
}



int find_file( char *path,char *des,char *file_name)
{	
	DIR				*dirp=NULL;
	struct	dirent	*direntp=NULL;
	int				found=0;
	int				rv=0;

	dirp=opendir(path);
	if(!dirp)
	{
		log_error("Open the %s directory failure: %s",path,strerror(errno));
		rv= -1;
	}

	printf("Open the directory success\n");

	while(NULL!=(direntp=readdir(dirp)))
	{
		if(strstr(direntp->d_name,des))
		{
			strncpy(file_name,direntp->d_name,64);
			found=1;
		}
	}
	

	if(!found)
	{
		log_error("Find temperature failure: %s\n",strerror(errno));
		rv= -2;
	}

	closedir(dirp);

	return rv;
}

